﻿using FxWinSupper.Config;
using System;
using System.Collections.Generic;
using System.Security;

namespace FxWinSuper.Plugin.Extension
{
	/// <summary>
	/// 外部配置文件工具类
	/// </summary>
	public static class ConfigUtil
	{
		/// <summary>
		/// 软件版本
		/// </summary>
		public static int VersionCode => Conf.VersionCode;

		public static string Version => Conf.Version;


		/// <summary>
		/// 读取配置项
		/// </summary>
		/// <param name="configName">配置项名</param>
		/// <param name="pwd">配置密码</param>
		/// <returns>读取到的配置</returns>
		public static string ReadConfig(string configName, string pwd)
		{
			if (!Conf.ExternalConfigs.ContainsKey(configName))
			{
				throw new KeyNotFoundException($"未获取到配置名为:{configName}的配置项.");
			}

			ExternalConfig config = Conf.ExternalConfigs[configName];
			if (config.ConfigPwd != pwd)
			{
				throw new SecurityException("配置项密码不正确，获取失败");
			}

			return config.ConfigContent;
		}

		/// <summary>
		/// 写入配置项
		/// </summary>
		/// <param name="configName">配置名</param>
		/// <param name="pwd">配置密码</param>
		/// <param name="configContent">配置详情</param>
		public static void WriteConfig(string configName, string pwd, string configContent)
		{
			if (string.IsNullOrWhiteSpace(pwd))
			{
				throw new ArgumentException("pwd不可为空");
			}

			ExternalConfig config;
			Conf.ExternalConfigs.TryGetValue(configName, out config);
			if (config == null)
			{
				config = new ExternalConfig()
				{
					ConfigName = configName,
					ConfigPwd = pwd,
					ConfigContent = configContent
				};
			}

			if (config.ConfigPwd != pwd)
			{
				throw new SecurityException("配置项密码不正确，写入失败");
			}

			config.ConfigContent = configContent;
			config.ConfigName = configName;
			Conf.ExternalConfigs[configName] = config;
			Conf.SaveConf();
		}
	}
}
